<template>
  <el-dialog
    v-model="dialogVisible"
    title="任务详情"
    :width="isMobile ? '90%' : '800px'"
    class="task-detail-dialog"
  >
    <div v-if="task" class="task-detail">
      <div class="task-header">
        <div class="task-title">
          <h2>{{ task.skillName }}</h2>
          <el-tag :type="getTaskStatusType">{{ getTaskStatusText }}</el-tag>
        </div>
        <div class="task-meta">
          <div class="meta-item">
            <el-icon><Calendar /></el-icon>
            <span>创建时间：{{ formatDate(task.createTime) }}</span>
          </div>
          <div class="meta-item" v-if="task.isCompleted === 2">
            <el-icon><Timer /></el-icon>
            <span>完成时间：{{ formatDate(task.completedTime) }}</span>
          </div>
        </div>
      </div>

      <div class="task-description">
        <h3>任务描述</h3>
        <p>{{ task.description }}</p>
      </div>

      <div class="task-progress">
        <h3>任务进度</h3>
        <el-progress 
          :percentage="calculateTaskProgress" 
          :status="getTaskProgressStatus"
        />
        <div class="progress-info">
          <span>已完成 {{ getCompletedNodesCount }} 个节点</span>
          <span>总计 {{ getTotalNodesCount }} 个节点</span>
        </div>
      </div>

      <div class="task-stages">
        <h3>任务阶段</h3>
        <el-timeline>
          <el-timeline-item
            v-for="stage in task.stageVos"
            :key="stage.id"
            :type="getStageStatusType(stage)"
            :hollow="!isStageCompleted(stage)"
          >
            <div class="stage-content">
              <h4>{{ stage.name }}</h4>
              <p class="stage-description">{{ stage.description }}</p>
              <div class="nodes-grid">
                <div
                  v-for="node in stage.nodes"
                  :key="node.id"
                  class="node-item"
                  :class="{ 'completed': node.completed }"
                >
                  <div class="node-content">
                    <el-icon v-if="node.completed"><Check /></el-icon>
                    <span>{{ node.name }}</span>
                  </div>
                </div>
              </div>
            </div>
          </el-timeline-item>
        </el-timeline>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="danger" @click="handleDelete" :loading="deleting">
          删除任务
        </el-button>
        <el-button @click="dialogVisible = false">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { Calendar, Timer, Check } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { deleteSkill } from '@/api/skill'

const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true
  },
  task: {
    type: Object,
    required: true
  }
})

const emit = defineEmits(['update:modelValue', 'deleted'])

const dialogVisible = ref(props.modelValue)
const deleting = ref(false)

// 添加移动端检测
const isMobile = ref(window.innerWidth <= 768)

// 监听窗口大小变化
window.addEventListener('resize', () => {
  isMobile.value = window.innerWidth <= 768
})

// 监听对话框显示状态
watch(() => props.modelValue, (val) => {
  dialogVisible.value = val
})

watch(() => dialogVisible.value, (val) => {
  emit('update:modelValue', val)
})

// 计算属性
const calculateTaskProgress = computed(() => {
  const totalNodes = getTotalNodesCount.value
  const completedNodes = getCompletedNodesCount.value
  return Math.round((completedNodes / totalNodes) * 100)
})

const getTaskProgressStatus = computed(() => {
  const progress = calculateTaskProgress.value
  if (progress >= 100) return 'success'
  if (progress >= 50) return 'warning'
  return ''
})

const getTaskStatusType = computed(() => {
  if (props.task.completedAt) return 'success'
  const progress = calculateTaskProgress.value
  if (progress >= 50) return 'warning'
  return 'info'
})

const getTaskStatusText = computed(() => {
  if (props.task.completedAt) return '已完成'
  const progress = calculateTaskProgress.value
  if (progress >= 50) return '进行中'
  return '刚开始'
})

const getTotalNodesCount = computed(() => {
  return props.task.stageVos.reduce((total, stage) => total + stage.nodes.length, 0)
})

const getCompletedNodesCount = computed(() => {
  return props.task.stageVos.reduce((total, stage) => {
    return total + stage.nodes.filter(node => node.completed).length
  }, 0)
})

// 方法
const formatDate = (date) => {
  return new Date(date).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const getStageStatusType = (stage) => {
  if (isStageCompleted(stage)) return 'success'
  if (isStageInProgress(stage)) return 'warning'
  return 'info'
}

const isStageCompleted = (stage) => {
  return stage.nodes.every(node => node.completed)
}

const isStageInProgress = (stage) => {
  return stage.nodes.some(node => node.completed)
}

const handleDelete = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这个任务吗？此操作不可恢复。',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    deleting.value = true
    await deleteSkill(props.task.id)
    ElMessage.success('删除成功')
    dialogVisible.value = false
    emit('deleted', props.task.id)
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  } finally {
    deleting.value = false
  }
}
</script>

<style scoped>
.task-detail-dialog :deep(.el-dialog__body) {
  padding: 24px;
}

.task-detail {
  max-height: 70vh;
  overflow-y: auto;
}

.task-header {
  margin-bottom: 24px;
}

.task-title {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 16px;
}

.task-title h2 {
  margin: 0;
  font-size: 20px;
  color: #303133;
}

.task-meta {
  display: flex;
  gap: 24px;
  color: #606266;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.meta-item .el-icon {
  font-size: 16px;
  color: #909399;
}

.task-description,
.task-progress,
.task-stages {
  margin-bottom: 24px;
}

.task-description h3,
.task-progress h3,
.task-stages h3 {
  font-size: 16px;
  color: #303133;
  margin: 0 0 16px 0;
}

.task-description p {
  color: #606266;
  line-height: 1.6;
  margin: 0;
}

.progress-info {
  display: flex;
  justify-content: space-between;
  margin-top: 8px;
  color: #909399;
  font-size: 14px;
}

.stage-content {
  padding: 8px 0;
}

.stage-content h4 {
  margin: 0 0 8px 0;
  font-size: 15px;
  color: #303133;
}

.stage-description {
  color: #606266;
  margin: 0 0 16px 0;
  font-size: 14px;
}

.nodes-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 12px;
}

.node-item {
  aspect-ratio: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  background: #f5f7fa;
  padding: 12px;
  text-align: center;
  font-size: 14px;
  border: 1px solid #dcdfe6;
  min-height: 80px;
}

.node-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  width: 100%;
}

.node-item.completed {
  background: #67c23a;
  color: white;
  border-color: #67c23a;
}

.node-item .el-icon {
  font-size: 20px;
}

.node-item.completed .node-content {
  color: white;
}

/* 移动端适配 */
@media screen and (max-width: 768px) {
  .task-detail-dialog :deep(.el-dialog__body) {
    padding: 16px;
  }

  .task-detail {
    max-height: 80vh;
  }

  .task-header {
    margin-bottom: 16px;
  }

  .task-title {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
    margin-bottom: 12px;
  }

  .task-title h2 {
    font-size: 18px;
  }

  .task-meta {
    flex-direction: column;
    gap: 8px;
  }

  .meta-item {
    font-size: 13px;
  }

  .task-description,
  .task-progress,
  .task-stages {
    margin-bottom: 16px;
  }

  .task-description h3,
  .task-progress h3,
  .task-stages h3 {
    font-size: 15px;
    margin-bottom: 12px;
  }

  .task-description p {
    font-size: 13px;
  }

  .progress-info {
    font-size: 13px;
  }

  .stage-content h4 {
    font-size: 14px;
  }

  .stage-description {
    font-size: 13px;
    margin-bottom: 12px;
  }

  .nodes-grid {
    grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
    gap: 8px;
  }

  .node-item {
    min-height: 70px;
    padding: 8px;
    font-size: 13px;
  }

  .node-item .el-icon {
    font-size: 18px;
  }

  .dialog-footer {
    flex-direction: column-reverse;
    gap: 8px;
  }
  
  .dialog-footer .el-button {
    width: 100%;
  }
}

/* 确保确认弹窗居中显示 */
:deep(.el-message-box) {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  margin: 0 !important;
}

:deep(.el-message-box__wrapper) {
  display: flex;
  align-items: center;
  justify-content: center;
}
</style> 